package xinyu.customer.login;

import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.text.TextUtils;
import android.view.View;

import com.alibaba.fastjson.JSON;
import com.logos.common.MainActivity;
import com.netease.nim.uikit.api.NimUIKit;
import com.netease.nimlib.sdk.NIMClient;
import com.netease.nimlib.sdk.NimIntent;
import com.netease.nimlib.sdk.mixpush.MixPushService;
import com.netease.nimlib.sdk.msg.MessageBuilder;
import com.netease.nimlib.sdk.msg.constant.SessionTypeEnum;
import com.netease.nimlib.sdk.msg.model.IMMessage;
import com.sh.sdk.shareinstall.ShareInstall;
import com.sh.sdk.shareinstall.listener.AppGetInfoListener;
import com.zxy.tiny.common.Logger;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.Map;

import xinyu.customer.R;
import xinyu.customer.base.AppBaseActivity;
import xinyu.customer.cache.LoginCache;
import xinyu.customer.chat.mixpush.DemoMixPushMessageHandler;
import xinyu.customer.home.HomeActivity;
import xinyu.customer.util.Preferences;
import xinyu.customer.util.SPUtils;
import xinyu.customer.util.SpConstant;
import xinyu.customer.util.SysInfoUtil;

public class SplashActivity extends AppBaseActivity {

    private Context mContext;
    private boolean customSplash = false;
    private static boolean firstEnter = true; // 是否首次进入


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_splash);
        mContext = this;
        LoginCache.setMainTaskLaunching(true);
        if (savedInstanceState != null) {
            setIntent(new Intent()); // 从堆栈恢复，不再重复解析之前的intent
        }
        if (!firstEnter) {
            onIntent(); // APP进程还在，Activity被重新调度起来
        } else {
            showSplashView(); // APP进程重新起来
        }
    }

    private void showSplashView() {
        // 首次进入，打开欢迎界面
        customSplash = true;
        initShareInstall(getIntent());
    }


    private void onIntent() {
        if (TextUtils.isEmpty(LoginCache.getAccount())) {
            // 判断当前app是否正在运行
            if (!SysInfoUtil.stackResumed(this)) {
                showToMainActivity(null);
            }
        } else {
            // 已经登录过了，处理过来的请求
            Intent intent = getIntent();
            if (intent != null) {
                if (intent.hasExtra(NimIntent.EXTRA_NOTIFY_CONTENT)) {
                    parseNotifyIntent(intent);
                    return;
                } else if (NIMClient.getService(MixPushService.class).isFCMIntent(intent)) {
                    parseFCMNotifyIntent(NIMClient.getService(MixPushService.class).parseFCMPayload(intent));
                }
            }
            if (!firstEnter && intent == null) {
                finish();
            } else {
                showToMainActivity(intent);
            }
        }
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        setIntent(intent);
        if (!customSplash) {
            onIntent();
        }
        initShareInstall(intent);
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (firstEnter) {
            firstEnter = false;
            Runnable runnable = new Runnable() {
                @Override
                public void run() {
                    if (!NimUIKit.isInitComplete()) {
                        new Handler().postDelayed(this, 100);
                        return;
                    }
                    customSplash = false;
                    if (canAutoLogin()) {
                        onIntent();
                    } else {
                        showToMainActivity(null);
                    }
                }
            };
            if (customSplash) {
                new Handler().postDelayed(runnable, 1000);
            } else {
                runnable.run();
            }
        }
    }

    /**
     * 已经登陆过，自动登陆
     */
    private boolean canAutoLogin() {
        String account = Preferences.getUserAccount();
        String token = Preferences.getUserToken();

        return !TextUtils.isEmpty(account) && !TextUtils.isEmpty(token);
    }


    private void initShareInstall(Intent intent) {
        ShareInstall.getInstance().init(getApplicationContext());
        // 调用注册接口
        ShareInstall.getInstance().reportRegister();
        ShareInstall.getInstance().getInfo(intent, listener);
    }

    private AppGetInfoListener listener = new AppGetInfoListener() {
        @Override
        public void onGetInfoFinish(String s) {
            try {
                Logger.e("onGetInfoFinish:>>>>>json"+s);

                if (!TextUtils.isEmpty(s)){
                    JSONObject object = new JSONObject(s);
                    String sourceId = object.optString("cust_id");
                    String sek = object.optString("sek");
                    String refway =object.optString("refway");
                    SPUtils.put(mContext, SpConstant.KEY_SHAREINSTALL_CUST_ID, sourceId);
                    SPUtils.put(mContext, SpConstant.KEY_SHAREINSTALL_CUST_KEY, sek);
                    SPUtils.put(mContext, SpConstant.KEY_SHAREINSTALL_WAY_KEY, refway);
                }

            } catch (JSONException e) {
                e.printStackTrace();
                Logger.e("onGetInfoFinish:>>>>>JSONException:"+e.getMessage());
            }
        }
    };

    private void  showToMainActivity(Intent extras){
        if ( TextUtils.isEmpty(SpConstant.getSek()) || TextUtils.isEmpty( SpConstant.getUserId())||0==SpConstant.getUserFullCheck()) {
            gotoLogin();
        }else {
            Intent intent = new Intent();
            intent.setClass(this, HomeActivity.class);
            intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
            if (extras != null) {
                intent.putExtras(extras);
            }
            startActivity(intent);
            finish();
        }
    }

    //跳转到登录
    private void gotoLogin() {
        startActivity(new Intent(SplashActivity.this,SelectLoginActivity.class));
    }

    private void parseNotifyIntent(Intent intent) {
        ArrayList<IMMessage> messages = (ArrayList<IMMessage>) intent.getSerializableExtra(NimIntent.EXTRA_NOTIFY_CONTENT);
        if (messages == null || messages.size() > 1) {
            showToMainActivity(null);
        } else {
            showToMainActivity(new Intent().putExtra(NimIntent.EXTRA_NOTIFY_CONTENT, messages.get(0)));
        }
    }

    private void parseFCMNotifyIntent(String payloadString) {
        Map<String, String> payload = JSON.parseObject(payloadString, Map.class);
        String sessionId = payload.get(DemoMixPushMessageHandler.PAYLOAD_SESSION_ID);
        String type = payload.get(DemoMixPushMessageHandler.PAYLOAD_SESSION_TYPE);
        if (sessionId != null && type != null) {
            int typeValue = Integer.valueOf(type);
            IMMessage message = MessageBuilder.createEmptyMessage(sessionId, SessionTypeEnum.typeOfValue(typeValue), 0);
            showToMainActivity(new Intent().putExtra(NimIntent.EXTRA_NOTIFY_CONTENT, message));
        } else {
            showToMainActivity(null);
        }
    }







    @Override
    public void finish() {
        super.finish();
        overridePendingTransition(0, 0);
        LoginCache.setMainTaskLaunching(false);
    }
    @Override
    public void onDestroy() {
        super.onDestroy();
    }
    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        outState.clear();
    }
}
